package com.example.elm.Home_Page;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.ColorDrawable;
import android.location.Address;
import android.location.Geocoder;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.text.Editable;
import android.text.PrecomputedText;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.NumberPicker;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeAddress;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.amap.api.services.help.Inputtips;
import com.amap.api.services.help.InputtipsQuery;
import com.amap.api.services.help.Tip;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.example.elm.R;
import com.example.elm.SQL.Connection_SQL;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Add_New_Location extends AppCompatActivity implements PoiSearch.OnPoiSearchListener, Inputtips.InputtipsListener {

    LinearLayout save_location, add_set_nearby_location, add_search_location, choose_get_order_location, search_location, choose_house, choose_company, choose_school, choose_parent_house, choose_country_number, change_location_button;
    EditText input_location, set_door_number, set_name, set_phone_number;
    TextView city_text_view, set_location_name, set_location_address_name, country_number_text_view;
    ScrollView add_search_location_list_view, set_location_data, show_nearby_location;
    RadioGroup choose_sex;
    RelativeLayout change_the_location;
    LinearLayout last_choose_label;

    Marker marker;
    MapView mapView;
    private AMap aMap = null;
    private UiSettings mUiSettings;
    double lat, lng;
    String city = "", district = "", email = "", province = "";
    private PoiSearch poisearch;
    List<List<String>> nearby_location = new ArrayList<>();
    String[] country_number_name = new String[]{"中国大陸+86", "香港+852", "澳门+853", "台湾+886"};
    String[] country_number = new String[]{"+86", "+852", "+853", "+886"};
    String choose_which_label = "", choose_which_sex = "先生";
    boolean is_finish_upload = false;
    AlertDialog dialog;

    private class Loading_Nearby_Location_Thread extends Thread {

        double lat, lng;

        public Loading_Nearby_Location_Thread(double lat, double lng) {
            this.lat = lat;
            this.lng = lng;
        }

        @Override
        public void run() {

            nearby_location.clear();
            LatLonPoint point = new LatLonPoint(lat, lng);
            PoiSearch.Query query = new PoiSearch.Query("", "", "");
            query.setPageSize(50);
            query.setPageNum(0);
            try {
                poisearch = new PoiSearch(Add_New_Location.this, query);
            } catch (AMapException e) {
                throw new RuntimeException(e);
            }
            poisearch.setOnPoiSearchListener(Add_New_Location.this);
            poisearch.setBound(new PoiSearch.SearchBound(point, 500, true));
            poisearch.searchPOIAsyn();

            while (nearby_location.isEmpty()) {
                try {
                    Thread.sleep(1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mUiSettings.setAllGesturesEnabled(true);

                    AnimationSet animationSet = (AnimationSet) AnimationUtils.loadAnimation(Add_New_Location.this, R.anim.slide_in_bottom);
                    show_nearby_location.startAnimation(animationSet);
                    show_nearby_location.setVisibility(View.VISIBLE);

                    animationSet = (AnimationSet) AnimationUtils.loadAnimation(Add_New_Location.this, R.anim.show_the_search_location);
                    search_location.setVisibility(View.VISIBLE);
                    search_location.startAnimation(animationSet);

                    add_set_nearby_location.removeAllViews();
                    for (int i = 0; i < nearby_location.size(); i++) {
                        View view = LayoutInflater.from(Add_New_Location.this).inflate(R.layout.add_new_location_nearby_location_view, null);
                        LinearLayout choose_this_location = view.findViewById(R.id.choose_this_location);
                        TextView address_aoi_name = view.findViewById(R.id.address_aoi_name);
                        TextView address_snippet = view.findViewById(R.id.address_snippet);
                        address_aoi_name.setText(nearby_location.get(i).get(0));
                        address_snippet.setText(nearby_location.get(i).get(1));

                        int finalI = i;
                        choose_this_location.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                mUiSettings.setAllGesturesEnabled(false);

                                AnimationSet animationSet = (AnimationSet) AnimationUtils.loadAnimation(Add_New_Location.this, R.anim.close_the_search_location);
                                search_location.startAnimation(animationSet);
                                search_location.setVisibility(View.INVISIBLE);

                                animationSet = (AnimationSet) AnimationUtils.loadAnimation(Add_New_Location.this, R.anim.slide_out_bottom);
                                show_nearby_location.startAnimation(animationSet);
                                show_nearby_location.setVisibility(View.GONE);

                                animationSet = (AnimationSet) AnimationUtils.loadAnimation(Add_New_Location.this, R.anim.slide_in_bottom);
                                set_location_data.startAnimation(animationSet);
                                set_location_data.setVisibility(View.VISIBLE);
                                change_the_location.setVisibility(View.VISIBLE);
                                choose_get_order_location.setVisibility(View.GONE);

                                set_location_name.setText(nearby_location.get(finalI).get(0));
                                set_location_address_name.setText(nearby_location.get(finalI).get(1));

                                marker.setPosition(new LatLng(Double.parseDouble(nearby_location.get(finalI).get(2)), Double.parseDouble(nearby_location.get(finalI).get(3))));
                                aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(Double.parseDouble(nearby_location.get(finalI).get(2)), Double.parseDouble(nearby_location.get(finalI).get(3))), 18));
                                lat = Double.parseDouble(nearby_location.get(finalI).get(2));
                                lng = Double.parseDouble(nearby_location.get(finalI).get(3));
                                district = nearby_location.get(finalI).get(4);
                                province = nearby_location.get(finalI).get(5);

                                change_location_button.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        onStop();
                                        Loading_Nearby_Location_Thread loadingNearbyLocationThread = new Loading_Nearby_Location_Thread(Double.parseDouble(nearby_location.get(finalI).get(2)), Double.parseDouble(nearby_location.get(finalI).get(3)));
                                        loadingNearbyLocationThread.start();

                                        city = get_city(Double.parseDouble(nearby_location.get(finalI).get(2)), Double.parseDouble(nearby_location.get(finalI).get(3)));
                                        city_text_view.setText(city);

                                        AnimationSet animationSet = (AnimationSet) AnimationUtils.loadAnimation(Add_New_Location.this, R.anim.slide_out_bottom);
                                        set_location_data.startAnimation(animationSet);
                                        set_location_data.setVisibility(View.GONE);
                                        change_the_location.setVisibility(View.GONE);

                                        aMap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
                                            @Override
                                            public void onCameraChange(CameraPosition cameraPosition) {
                                                marker.setPosition(cameraPosition.target);
                                            }

                                            @Override
                                            public void onCameraChangeFinish(CameraPosition cameraPosition) {
                                                if (mUiSettings.isScrollGesturesEnabled()) {
                                                    onStop();
                                                    Loading_Nearby_Location_Thread loadingNearbyLocationThread = new Loading_Nearby_Location_Thread(cameraPosition.target.latitude, cameraPosition.target.longitude);
                                                    loadingNearbyLocationThread.start();
                                                }
                                            }
                                        });
                                    }
                                });
                            }
                        });

                        add_set_nearby_location.addView(view);
                    }
                }
            });
        }
    }

    private class Upload_Location_Data_Thread extends Thread {
        @Override
        public void run() {
            is_finish_upload = false;

            ExecutorService executorService = Executors.newSingleThreadExecutor();
            executorService.execute(() -> {
                try {
                    Connection_SQL connectionSql = new Connection_SQL();
                    Connection connection = connectionSql.connection();
                    String sql = "INSERT INTO `elm`.`" + email + "_user_location`(address, door_number, label, name, phone_number, lat, lng, is_sir, city, district, province) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);";
                    PreparedStatement preparedStatement = connection.prepareStatement(sql);
                    preparedStatement.setString(1, set_location_name.getText().toString());
                    preparedStatement.setString(2, set_door_number.getText().toString());
                    preparedStatement.setString(3, choose_which_label);
                    preparedStatement.setString(4, set_name.getText().toString());
                    preparedStatement.setString(5, set_phone_number.getText().toString());
                    preparedStatement.setDouble(6, lat);
                    preparedStatement.setDouble(7, lng);
                    if (choose_which_sex.equals("先生")) {
                        preparedStatement.setInt(8, 1);
                    }
                    else {
                        preparedStatement.setInt(8, 0);
                    }
                    preparedStatement.setString(9, get_city(lat, lng));
                    preparedStatement.setString(10, district);
                    preparedStatement.setString(11, province);
                    preparedStatement.executeUpdate();
                    is_finish_upload = true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

            while (!is_finish_upload) {
                try {
                    Thread.sleep(1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    dialog.dismiss();
                    Intent intent = new Intent(Add_New_Location.this, Set_Location_Page.class);
                    setResult(2, intent);
                    finish();
                }
            });
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_new_location);

        lat = getIntent().getDoubleExtra("lat", 0);
        lng = getIntent().getDoubleExtra("lng", 0);
        city = getIntent().getStringExtra("city");
        district = getIntent().getStringExtra("district");
        email = getIntent().getStringExtra("email");

        add_set_nearby_location = findViewById(R.id.add_set_nearby_location);
        input_location = findViewById(R.id.input_location);
        city_text_view = findViewById(R.id.city);
        add_search_location = findViewById(R.id.add_search_location);
        add_search_location_list_view = findViewById(R.id.add_search_location_list_view);
        choose_get_order_location = findViewById(R.id.choose_get_order_location);
        set_location_data = findViewById(R.id.set_location_data);
        show_nearby_location = findViewById(R.id.show_nearby_location);
        search_location = findViewById(R.id.search_location);
        choose_house = findViewById(R.id.choose_house);
        choose_company = findViewById(R.id.choose_company);
        choose_parent_house = findViewById(R.id.choose_parent_house);
        choose_school = findViewById(R.id.choose_school);
        set_door_number = findViewById(R.id.set_door_number);
        set_name = findViewById(R.id.set_name);
        set_phone_number = findViewById(R.id.set_phone_number);
        choose_sex = findViewById(R.id.choose_sex);
        choose_country_number = findViewById(R.id.choose_country_number);
        change_the_location = findViewById(R.id.change_the_location);
        set_location_name = findViewById(R.id.set_location_name);
        set_location_address_name = findViewById(R.id.set_location_address_name);
        change_location_button = findViewById(R.id.change_location_button);
        save_location = findViewById(R.id.save_location);
        country_number_text_view = findViewById(R.id.country_number_text_view);

        choose_location();

        city_text_view.setText(city);
        city_text_view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Add_New_Location.this, Choose_City_Page.class);
                intent.putExtra("city_text", city);
                startActivityForResult(intent, 1);
            }
        });

        input_location.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (!input_location.getText().toString().isEmpty()) {
                    add_search_location_list_view.setVisibility(View.VISIBLE);
                    add_search_location.removeAllViews();
                    InputtipsQuery inputquery = new InputtipsQuery(input_location.getText().toString(), city);
                    inputquery.setCityLimit(true); //限制在当前城市

                    Inputtips inputTips = new Inputtips(Add_New_Location.this, inputquery);
                    inputTips.setInputtipsListener(Add_New_Location.this);
                    inputTips.requestInputtipsAsyn();
                }
                else {
                    add_search_location_list_view.setVisibility(View.GONE);
                    add_search_location.removeAllViews();
                }
            }
        });

        initMap(savedInstanceState);
    }

    private void initMap(Bundle savedInstanceState) {
        LatLng latLng = new LatLng(lat, lng);
        mapView = findViewById(R.id.map);
        //在activity执行onCreate时执行mMapView.onCreate(savedInstanceState)，创建地图
        mapView.onCreate(savedInstanceState);
        //初始化地图控制器对象
        aMap = mapView.getMap();

        aMap.setPointToCenter(getResources().getDisplayMetrics().widthPixels / 2, getResources().getDisplayMetrics().heightPixels / 4);

        // 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        //aMap.setMyLocationEnabled(true);
        //aMap.setMinZoomLevel(12);
        mUiSettings = aMap.getUiSettings();
        mUiSettings.setZoomControlsEnabled(false);

        mUiSettings.setMyLocationButtonEnabled(true); //显示默认的定位
        mUiSettings.setAllGesturesEnabled (false);

        //aMap.setMyLocationEnabled(false);// 可触发定位并显示当前位置

        //myLocationStyle.interval(2000);
        //myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE);
        aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 18));

        marker = aMap.addMarker(new MarkerOptions().position(latLng).title(city).snippet("DefaultMarker"));
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        mapView.onPause();
    }
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mapView.onSaveInstanceState(outState);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        mapView.onDestroy();
    }

    @Override
    public void onPoiSearched(PoiResult poiResult, int i) {
        if (i == AMapException.CODE_AMAP_SUCCESS) {
            if (poiResult != null && poiResult.getPois().size() > 0) {
                nearby_location.clear();
                List<PoiItem> poiItems = poiResult.getPois();
                for (PoiItem poiItem : poiItems) {
                    List<String> temp = new ArrayList<>();
                    temp.add(poiItem.getTitle());
                    temp.add(poiItem.getSnippet());
                    temp.add(String.valueOf(poiItem.getLatLonPoint().getLatitude()));
                    temp.add(String.valueOf(poiItem.getLatLonPoint().getLongitude()));
                    temp.add(poiItem.getAdName());
                    temp.add(poiItem.getProvinceName());
                    nearby_location.add(temp);
                }
            } else {
                Toast.makeText(this, "无搜索结果", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(this, "搜索失败", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {

    }

    @Override
    public void onGetInputtips(List<Tip> list, int i) {
        for (int j = 0; j < list.size(); j++) {
            View view = LayoutInflater.from(Add_New_Location.this).inflate(R.layout.add_new_location_nearby_location_view, null);
            TextView address_aoi_name = view.findViewById(R.id.address_aoi_name);
            TextView address_snippet = view.findViewById(R.id.address_snippet);
            LinearLayout choose_this_location = view.findViewById(R.id.choose_this_location);
            address_aoi_name.setText(list.get(j).getName());
            address_snippet.setText(list.get(j).getAddress());

            int finalJ = j;
            choose_this_location.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    add_search_location_list_view.setVisibility(View.GONE);
                    add_search_location.removeAllViews();
                    AnimationSet animationSet = (AnimationSet) AnimationUtils.loadAnimation(Add_New_Location.this, R.anim.close_the_search_location);
                    search_location.startAnimation(animationSet);
                    search_location.setVisibility(View.INVISIBLE);

                    animationSet = (AnimationSet) AnimationUtils.loadAnimation(Add_New_Location.this, R.anim.slide_out_bottom);
                    show_nearby_location.startAnimation(animationSet);
                    show_nearby_location.setVisibility(View.GONE);

                    animationSet = (AnimationSet) AnimationUtils.loadAnimation(Add_New_Location.this, R.anim.slide_in_bottom);
                    set_location_data.startAnimation(animationSet);
                    set_location_data.setVisibility(View.VISIBLE);
                    change_the_location.setVisibility(View.VISIBLE);
                    choose_get_order_location.setVisibility(View.GONE);

                    set_location_name.setText(list.get(finalJ).getName());
                    set_location_address_name.setText(list.get(finalJ).getAddress());
                    marker.setPosition(new LatLng(list.get(finalJ).getPoint().getLatitude(), list.get(finalJ).getPoint().getLongitude()));
                    aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(list.get(finalJ).getPoint().getLatitude(), list.get(finalJ).getPoint().getLongitude()), 18));
                    input_location.setText("");
                    lat = list.get(finalJ).getPoint().getLatitude();
                    lng = list.get(finalJ).getPoint().getLongitude();
                    district = "";
                    for (int i = list.get(finalJ).getDistrict().indexOf(city) + city.length(); i < list.get(finalJ).getDistrict().length(); i++) {
                        district += list.get(finalJ).getDistrict().charAt(i);
                    }
                    province = "";
                    for (int i = 0; i < list.get(finalJ).getDistrict().indexOf(city); i++) {
                        province += list.get(finalJ).getDistrict().charAt(i);
                    }

                    change_location_button.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            onStop();
                            Loading_Nearby_Location_Thread loadingNearbyLocationThread = new Loading_Nearby_Location_Thread(list.get(finalJ).getPoint().getLatitude(), list.get(finalJ).getPoint().getLongitude());
                            loadingNearbyLocationThread.start();

                            city = get_city(list.get(finalJ).getPoint().getLatitude(), list.get(finalJ).getPoint().getLongitude());
                            city_text_view.setText(city);

                            AnimationSet animationSet = (AnimationSet) AnimationUtils.loadAnimation(Add_New_Location.this, R.anim.slide_out_bottom);
                            set_location_data.startAnimation(animationSet);
                            set_location_data.setVisibility(View.GONE);
                            change_the_location.setVisibility(View.GONE);

                            aMap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
                                @Override
                                public void onCameraChange(CameraPosition cameraPosition) {
                                    marker.setPosition(cameraPosition.target);
                                }

                                @Override
                                public void onCameraChangeFinish(CameraPosition cameraPosition) {
                                    if (mUiSettings.isScrollGesturesEnabled()) {
                                        onStop();
                                        Loading_Nearby_Location_Thread loadingNearbyLocationThread = new Loading_Nearby_Location_Thread(cameraPosition.target.latitude, cameraPosition.target.longitude);
                                        loadingNearbyLocationThread.start();
                                    }
                                }
                            });
                        }
                    });
                }
            });

            add_search_location.addView(view);
        }
    }

    void choose_location() {

        choose_get_order_location.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Loading_Nearby_Location_Thread loadingNearbyLocationThread = new Loading_Nearby_Location_Thread(lat, lng);
                loadingNearbyLocationThread.start();

                city = get_city(lat, lng);
                city_text_view.setText(city);

                AnimationSet animationSet = (AnimationSet) AnimationUtils.loadAnimation(Add_New_Location.this, R.anim.slide_out_bottom);
                set_location_data.startAnimation(animationSet);
                set_location_data.setVisibility(View.GONE);
                change_the_location.setVisibility(View.GONE);

                aMap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
                    @Override
                    public void onCameraChange(CameraPosition cameraPosition) {
                        marker.setPosition(cameraPosition.target);
                    }

                    @Override
                    public void onCameraChangeFinish(CameraPosition cameraPosition) {
                        if (mUiSettings.isScrollGesturesEnabled()) {
                            onStop();
                            Loading_Nearby_Location_Thread loadingNearbyLocationThread = new Loading_Nearby_Location_Thread(cameraPosition.target.latitude, cameraPosition.target.longitude);
                            loadingNearbyLocationThread.start();
                        }
                    }
                });
            }
        });

        choose_sex.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                RadioButton type = findViewById(radioGroup.getCheckedRadioButtonId());
                choose_which_sex = type.getText().toString();
            }
        });

        choose_house.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                choose_house.setBackgroundResource(R.drawable.border_5dp_white_2);
                if (last_choose_label != null) {
                    last_choose_label.setBackgroundResource(R.drawable.border_light_gray_5dp_no_background);
                }
                if (choose_which_label.equals("家")) {
                    choose_which_label = "";
                    last_choose_label = null;
                }
                else {
                    choose_which_label = "家";
                    last_choose_label = choose_house;
                }
            }
        });

        choose_company.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                choose_company.setBackgroundResource(R.drawable.border_5dp_white_2);
                if (last_choose_label != null) {
                    last_choose_label.setBackgroundResource(R.drawable.border_light_gray_5dp_no_background);
                }
                if (choose_which_label.equals("公司")) {
                    choose_which_label = "";
                    last_choose_label = null;
                }
                else {
                    choose_which_label = "公司";
                    last_choose_label = choose_company;
                }
            }
        });

        choose_school.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                choose_school.setBackgroundResource(R.drawable.border_5dp_white_2);
                if (last_choose_label != null) {
                    last_choose_label.setBackgroundResource(R.drawable.border_light_gray_5dp_no_background);
                }
                if (choose_which_label.equals("学校")) {
                    choose_which_label = "";
                    last_choose_label = null;
                }
                else {
                    choose_which_label = "学校";
                    last_choose_label = choose_school;
                }
            }
        });

        choose_parent_house.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                choose_parent_house.setBackgroundResource(R.drawable.border_5dp_white_2);
                if (last_choose_label != null) {
                    last_choose_label.setBackgroundResource(R.drawable.border_light_gray_5dp_no_background);
                }
                if (choose_which_label.equals("父母家")) {
                    choose_which_label = "";
                    last_choose_label = null;
                }
                else {
                    choose_which_label = "父母家";
                    last_choose_label = choose_parent_house;
                }
            }
        });

        choose_country_number.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Dialog dialog = new Dialog(view.getContext());
                dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
                dialog.setContentView(R.layout.set_country_number_dialog);

                TextView save = dialog.findViewById(R.id.save);
                TextView cancel = dialog.findViewById(R.id.cancel);

                cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        dialog.dismiss();
                    }
                });

                NumberPicker numberPicker = dialog.findViewById(R.id.choose_country_number);
                numberPicker.setMaxValue(country_number_name.length - 1);
                numberPicker.setDisplayedValues(country_number_name);
                numberPicker.setMinValue(0);
                numberPicker.setValue(0);

                save.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        country_number_text_view.setText(country_number[numberPicker.getValue()]);
                        dialog.dismiss();
                    }
                });

                dialog.show();
                dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                dialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation;
                dialog.getWindow().setGravity(Gravity.BOTTOM);
            }
        });

        save_location.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (choose_get_order_location.getVisibility() == View.VISIBLE) {
                    Toast.makeText(Add_New_Location.this, "请先选择地址", Toast.LENGTH_SHORT).show();
                }
                else if (set_door_number.getText().toString().isEmpty() || set_name.getText().toString().isEmpty() || set_phone_number.getText().toString().isEmpty()) {
                    Toast.makeText(Add_New_Location.this, "请输入所有内容", Toast.LENGTH_SHORT).show();
                }
                else {
                    set_dialog();
                    Upload_Location_Data_Thread uploadLocationDataThread = new Upload_Location_Data_Thread();
                    uploadLocationDataThread.start();
                }
            }
        });
    }

    public String get_city(double lat, double lng) {
        Geocoder geocoder = new Geocoder(this, Locale.getDefault());
        try {
            List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
            if (!addresses.isEmpty()) {
                return addresses.get(0).getLocality();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public void set_dialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        LayoutInflater inflater1 = LayoutInflater.from(this);
        builder.setView(inflater1.inflate(R.layout.loading, null));
        builder.setCancelable(false);

        dialog = builder.create();
        dialog.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case 1: {
                if (data != null) {
                    city = data.getStringExtra("city_name");
                    city_text_view.setText(city);
                }
            }
        }
    }
}